package com.fanhang.samples.spring.hibernate.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fanhang.samples.spring.hibernate.dao.UserDao;
import com.fanhang.samples.spring.hibernate.model.User;

/**
 * jdbc
 * @author fanhang
 *
 */
@Repository
public class UserDaoImpl implements UserDao {

	@Autowired
	protected SessionFactory sessionFactory;
	
	@Override
	public int save(User model) {
		sessionFactory.getCurrentSession().persist(model);
		return 1;
	}

	@Override
	public int delete(Integer id) {
		sessionFactory.getCurrentSession().delete(id);
		return 1;
	}

	@Override
	public int update(User model) {
		sessionFactory.getCurrentSession().update(model);
		return 1;
	}

	@Override
	public User get(Long id) {
		return (User) sessionFactory.getCurrentSession().get(User.class, id);
	}

	@Override
	public List<User> getList(User model) {
		Criteria c = sessionFactory.getCurrentSession().createCriteria(User.class);
//		c.add(Restrictions.like("name", model.getName(), MatchMode.ANYWHERE));
		return c.add(Example.create(model)).list();
	}
}
